package com.lyl.syt.modules.mq.receiver;/**
 * @author Mr.Luo
 * @date 2022-05-25 10:42
 */

import com.lyl.syt.model.hosp.Schedule;
import com.lyl.syt.modules.mongodb.service.ScheduleService;
import com.lyl.syt.rabbit.constant.MqConstant;
import com.lyl.syt.rabbit.service.RabbitService;
import com.lyl.syt.vo.msm.MsmVo;
import com.lyl.syt.vo.order.OrderMqVo;
import com.rabbitmq.client.Channel;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

/**
 * @author Mr.Luo
 * @date 2022-05-25 10:42
 * @desc
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class HospitalReceiver {
    private final ScheduleService scheduleService;
    private final RabbitService rabbitService;

    @RabbitListener(bindings = {@QueueBinding(
            value = @Queue(value = MqConstant.ORDER_QUEUE, durable = "true"),
            exchange = @Exchange(value = MqConstant.ORDER_EXCHANGE),
            key = {MqConstant.ORDER_ROUTING}
    )})
    public void receiver(OrderMqVo mqVo, Message message, Channel channel) {
        log.info("接受到[{}]队列的消息，消息内容是: {} ", MqConstant.ORDER_QUEUE, mqVo);
        Schedule schedule = scheduleService.getScheduleById(mqVo.getScheduleId());
        if (mqVo.getAvailableNumber() != null) {
            //下单成功更新预约数
            schedule.setAvailableNumber(mqVo.getAvailableNumber());
            schedule.setReservedNumber(mqVo.getReservedNumber());
        } else {
            //取消预约更新预约数
            int availableNumber = schedule.getAvailableNumber().intValue() + 1;
            schedule.setAvailableNumber(availableNumber);
        }
        //下单成功更新预约数
        scheduleService.update(schedule);
        //发送短信通知
        MsmVo msmVo = mqVo.getMsmVo();
        if (msmVo != null) {
            rabbitService.sendMessage(MqConstant.MSM_EXCHANGE, MqConstant.MSM_ROUTING, msmVo);
        }
    }


}
